import {Component, EventEmitter, Input, Output, OnInit} from '@angular/core';
import {ResetPasswordService} from './reset-password.service';
import {NzMessageService} from 'ng-zorro-antd';
import {FormBuilder} from '@angular/forms';
import {CustomValidators} from '@kylin/validators';

@Component({
  selector: 'kylin-user-modify-password',
  templateUrl: './reset-password.component.html',
  styleUrls: ['./reset-password.component.less']
})
export class ResetPasswordComponent implements OnInit {
    @Input() isVisible = false;
    @Output() isVisibleChange = new EventEmitter<boolean>();
    @Input() userInfo: any;
    submitLoading = false;
    newPassword = '';
    loading = false;

    constructor(fb: FormBuilder, private resetSvc: ResetPasswordService, private message: NzMessageService) {

    }

    ngOnInit() {
    }

    closeModal() {
        this.isVisible = false;
        this.isVisibleChange.emit(false);
    }

    passwordFormatValidator() {
        // 校验通过返回true
        const newPasswordValidate = CustomValidators.passwordValidator()({value: this.newPassword}as any);
        return !(newPasswordValidate);
    }

    submit() {
        this.loading = true;
        if (!this.newPassword) {
            this.message.warning('请输入新密码');
        } else if (!this.passwordFormatValidator()) {
            this.message.error('请输入正确格式的密码，密码由8-16位大写、小写字母，数字和特殊字符中的三种或四种组成');
            return;
        } else {
            this.resetSvc.resetPassword({
                id: this.userInfo.id,
                newPassword: this.newPassword
            }).then(rep => {
                if (rep.resp_code === '10000') {
                    this.message.success(`用户 ${this.userInfo.username} 密码重置成功`);
                    this.closeModal();
                } else {
                    this.message.error(`用户 ${this.userInfo.username} 密码重置失败：${rep.resp_msg}`);
                }
                this.loading = false;
            });
        }
    }
}
